import { SYS_SETTINGS } from './sys-settings';
import { ApplicationContainer } from './core/service/application-container';
import { getApplicationContainer } from './get-application-container';

const applicationContainerIns = new ApplicationContainer(SYS_SETTINGS);
const DEFAULT_FORWARD = 'https://xq-treasure-community.oss-cn-shanghai.aliyuncs.com/ads/index-banner-4.jpg';
// app.ts
App<IAppOption>({
    globalData: {
        applicationContainer: applicationContainerIns,
        systemInfo: wx.getSystemInfoSync(),
        default_forward: DEFAULT_FORWARD
    },
    onLaunch() {
        // 展示本地存储能力
        // const logs = wx.getStorageSync('logs') || []
        // logs.unshift(Date.now())
        // wx.setStorageSync('logs', logs)


        // // 登录
        // wx.login({
        //     success: res => {
        //         console.log(res.code)
        //         // 发送 res.code 到后台换取 openId, sessionKey, unionId
        //     },
        // });

        // // 获取用户信息
        
    },

    onError: function (error: any) {
        const prefix = 'error:';
        let errorMsg = error.split(/[\n]/)[1];
        let index = errorMsg.indexOf(prefix);
        if (index > -1) {
            errorMsg = errorMsg.substring(index + prefix.length);
        }
        getApplicationContainer().dialogService.alert(errorMsg);
    },

    onUnhandledRejection(error: any) {
        let reason: {
            message: string,
            code: string
        } = {
            message: '出现异常',
            code: '0'
        };
        if (typeof error === 'string') {
            reason.message = error;
        } else if (error && error.reason) {
            if (typeof error.reason == 'string') {
                reason.message = error.reason;
            } else if (error.reason) {
                reason.message = error.reason.message;
                reason.code = error.reason.code;
            }
        }
        if (`${reason.code}` == "6406" && !isAuthPage()) {
            wx.redirectTo({
                url: '/pages/auth/index'
            });
        } else {
            applicationContainerIns.dialogService.alert(reason.message);
        }
    },

    onShow: function () {
        let pages = getCurrentPages();
        if (pages.length) {
            // 获取当前页面的对象（上边所获得的数组中最后一项就是当前页面的对象）
            let currPage = pages[pages.length - 1];
            if (!applicationContainerIns.authService.token && !isAuthPage()) {
                wx.redirectTo({
                    url: '/pages/auth/index'
                });
            }
        }
    },

    onPageNotFound: function (error: any) {

    }
} as any);

function isAuthPage() {
    let pages = getCurrentPages();
    if (pages.length) {
        // 获取当前页面的对象（上边所获得的数组中最后一项就是当前页面的对象）
        let currPage = pages[pages.length - 1];
        return currPage && currPage.route.indexOf('auth') > -1;
    }
    return false
}